package com.kkb.shopcenter.server.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kkb.shopcenter.api.GoodInfoService;
import com.kkb.shopcenter.common.constant.ConstantKey;
import com.kkb.shopcenter.common.pojo.GoodsAttach;
import com.kkb.shopcenter.common.pojo.GoodsInfo;
import com.kkb.shopcenter.common.pojo.GoodsQueryCondition;
import com.kkb.shopcenter.server.mappers.GoodsAttachMapper;
import com.kkb.shopcenter.server.mappers.GoodsInfoMapper;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class GoodInfoServiceImpl implements GoodInfoService {

    @Autowired
    private GoodsInfoMapper goodsInfoMapper;

    @Autowired
    private GoodsAttachMapper goodsAttachMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public PageInfo<GoodsInfo> queryAllByCondition(GoodsQueryCondition condition) {
        //开始设置分页
        PageHelper.startPage(condition.getPage()+1,condition.getSize());
        //组合查询条件
        Example example = new Example(GoodsInfo.class);
        if(condition.getId()!=null){
            example.createCriteria().andEqualTo("id",condition.getId());
        }

        //设置商品名称查询条件
        if(StringUtils.isNotEmpty(condition.getGoodsName())){
            example.createCriteria().andEqualTo("goodsName",condition.getGoodsName());
        }
        if(condition.getShopId()>0){
            example.createCriteria().andEqualTo("shopId",condition.getShopId());
        }
        if(condition.getStatus()!=null){
            example.createCriteria().andEqualTo("status",condition.getStatus());
        }
        //查询商品列表
        List<GoodsInfo> goodInfos = goodsInfoMapper.selectByExample(example);
        PageInfo<GoodsInfo> pageInfo = new PageInfo<>(goodInfos);
        return pageInfo;
    }

    @Override
    public int deleteImageByGoodsId(Long goodsId) {

        Example example = new Example(GoodsAttach.class);
        example.createCriteria().andEqualTo("goodsId",goodsId);

        return goodsAttachMapper.deleteByExample(example);
    }

    @Override
    public void releteImage(GoodsAttach attach) {
        goodsAttachMapper.insertSelective(attach);
    }

    @Override
    public List<GoodsAttach> getImgs(Long goodsId) {
        Example example = new Example(GoodsAttach.class);
        example.createCriteria().andEqualTo("goodsId",goodsId);
        return goodsAttachMapper.selectByExample(example);
    }

    @Override
    public int updateGoods(GoodsInfo goodsInfo) {
        int count = goodsInfoMapper.updateByPrimaryKeySelective(goodsInfo);
        rocketMQTemplate.convertAndSend(ConstantKey.TOPIC_NAME,goodsInfo);
        return count;
    }
}
